package com.tianjs.current.context;

/**
 * 一万次：并行需要9ms,串行需要1ms
 * 10万次：并行需要4ms,串行需要3ms
 * 100万次：并行需要6ms,串行需要6ms
 * 1000万次：并行需要12ms,串行需要14ms
 * 1亿次：并行需要80ms,串行需要95ms
 * 10亿次：并行需要494ms,串行需要781ms
 * 结论：计算次数越大，并行才有意义
 * 并行(上下文切换)和串行的计算对比
 * @author admin
 */
public class ContextSwitch {
	private static final long count = 1000000000l;

	public static void main(String[] args) throws InterruptedException {
		concurrency();
		seriral();
	}
	
	public static void concurrency() throws InterruptedException {
		long start = System.currentTimeMillis();
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				int a = 0;
				for(long i=0;i<count;i++) {
					a+=5;
				}
			}
		});
		thread.start();
		int b = 0;
		for(long i=0;i<count;i++) {
			b--;
		}
		thread.join();
		long time = System.currentTimeMillis() - start;
		System.out.println(""+time+"ms,b="+b+"");
	}

	public static void seriral() {
		long start = System.currentTimeMillis();
		int a = 0;
		for(long i=0;i<count;i++) {
			a+=5;
		}
		int b = 0;
		for(long i=0;i<count;i++) {
			b--;
		}
		long time = System.currentTimeMillis() - start;
		System.out.println(""+time+"ms,b="+b+",a="+a);
	}
}
